<template>
  <div class="purchase-container">
    <div class="course-card">
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="搜索课程..."
          prefix-icon="el-icon-search"
          clearable
          @clear="handleSearchClear"
          @input="handleSearch">
        </el-input>
      </div>
      
      <h3>课程购买</h3>
      <div class="course-grid">
        <el-card class="course-item" v-for="course in filteredCourses" :key="course.id">
          <div class="course-info">
            <h4>{{ course.name }}</h4>
            <p>{{ course.description }}</p>
            <p class="price">价格: {{ course.price }}</p>
          </div>
          <div class="course-actions">
            <el-button type="primary" @click="purchaseCourse(course)">购买</el-button>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchQuery: '',
      courses: [
        {
          id: 1,
          name: 'Vue.js入门课程',
          description: '从零开始学习Vue.js框架',
          price: '¥199'
        },
        {
          id: 2,
          name: 'Element UI实战',
          description: '掌握Element UI组件库的使用',
          price: '¥299'
        },
        {
          id: 3,
          name: 'Vue Router深度解析',
          description: '全面掌握Vue路由管理',
          price: '¥249'
        },
        {
          id: 4,
          name: 'Vuex状态管理',
          description: '学习Vuex的核心概念与应用',
          price: '¥279'
        },
        {
          id: 5,
          name: 'Vue 3.0新特性',
          description: '探索Vue 3.0的最新功能',
          price: '¥349'
        },
        {
          id: 6,
          name: 'Vue项目实战',
          description: '从零构建完整Vue项目',
          price: '¥399'
        },
        {
          id: 7,
          name: 'Vue性能优化',
          description: '提升Vue应用性能的技巧',
          price: '¥329'
        }
      ]
    }
  },
  computed: {
    filteredCourses() {
      if (!this.searchQuery) {
        return this.courses
      }
      const query = this.searchQuery.toLowerCase()
      return this.courses.filter(course => 
        course.name.toLowerCase().includes(query) || 
        course.description.toLowerCase().includes(query)
      )
    }
  },
  created() {
    // 从URL参数获取搜索关键词
    const urlSearch = this.$route.query.search;
    if (urlSearch) {
      this.searchQuery = urlSearch;
    }
  },
  methods: {
    isPurchased(courseId) {
      // 调用Vuex的getter方法检查课程是否已购买
      return this.$store.getters.isCourseAlreadyPurchased(courseId);
    },
    purchaseCourse(course) {
      // 检查登录状态
      const isLoggedIn = !!localStorage.getItem('user');
      if (!isLoggedIn) {
        this.$confirm('您需要登录才能购买课程，是否前往登录页面？', '提示', {
          confirmButtonText: '去登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 记录当前路径，登录后可以回来
          this.$router.push({
            path: '/login',
            query: { redirect: this.$route.fullPath }
          });
        }).catch(() => {
          this.$message.info('已取消购买');
        });
        return;
      }
      
      // 已登录，继续购买流程
      this.$confirm(`确定购买 ${course.name} 课程吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 生成新订单
        const newOrder = {
          id: '2023' + Math.floor(Math.random() * 9000 + 1000),
          course: course.name,
          price: course.price,
          status: '待支付',
          date: new Date().toISOString().split('T')[0]
        };
        
        // 通过Vuex将订单添加到订单列表
        this.$store.dispatch('addOrder', newOrder);
        this.$message.success('购买成功');
        // 跳转到支付页面
        this.$router.push(`/dashboard/payment/${newOrder.id}`);
      }).catch(() => {
        this.$message.info('已取消购买');
      });
    },
    studyCourse(courseId) {
      // 检查登录状态
      const isLoggedIn = !!localStorage.getItem('user');
      if (!isLoggedIn) {
        this.$confirm('您需要登录才能学习课程，是否前往登录页面？', '提示', {
          confirmButtonText: '去登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 记录当前路径，登录后可以回来
          this.$router.push({
            path: '/login',
            query: { redirect: this.$route.fullPath }
          });
        }).catch(() => {
          this.$message.info('已取消操作');
        });
        return;
      }
      
      // 检查课程是否已购买
      if (!this.isPurchased(courseId)) {
        this.$message.warning('请先购买该课程');
        return;
      }
      
      // 跳转到课程学习页面
      this.$router.push(`/dashboard/study/${courseId}`);
    },
    handleSearch() {
      // 搜索逻辑已通过计算属性实现
    },
    handleSearchClear() {
      this.searchQuery = ''
    }
  }
}
</script>

<style scoped>
.purchase-container {
  height: 100%;
  padding: 20px;
}

.course-card {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-bar {
  margin-bottom: 20px;
  width: 300px;
}

.course-card h3 {
  font-size: 24px;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  color: #303133;
}

.course-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.course-item {
  margin-bottom: 0;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;
  transition: all 0.3s ease;
}

.course-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.course-info {
  margin-bottom: 15px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
  margin-top: 10px;
}

.course-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
}

/* 响应式布局 */
@media screen and (max-width: 1200px) {
  .course-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media screen and (max-width: 768px) {
  .course-grid {
    grid-template-columns: 1fr;
  }
}
</style>